<?php
/**
 * Created by PhpStorm.
 * User: lee
 * Date: 2018/6/20
 * Time: 14:43
 */

namespace Biz\service\activity;

use Biz\model\activity\CouponConfig;
use Biz\model\activity\CouponRecord;
use Biz\model\ShopSwitch;
use Biz\module\Classes\adm\Coupon as clsAdmCoupon;
use Biz\module\Classes\Coupon as clsCoupon;
use Biz\module\Classes\ShopCoupon as clsShopCoupon;
use Biz\module\Classes\mgt\Coupon as clsMgtCoupon;
use Biz\model\activity\CouponConfig as mCouponConfig;
use Biz\model\activity\CouponRecord as mCouponRecord;
use Biz\service\Activitys;
use Biz\service\Goods;
use Biz\service\trade\Cart;
use Doraemon\tools\Log as tLog;
use Biz\model\GoodsBasicInfo as mGoodsBasicInfo;
use Biz\module\Classes\OutCoupon as clsOutCoupon;
use Biz\model\activity\OutCouponConfig as mOutCouponConfig;
use Biz\cache\Coupon as cCoupon;
use Biz\model\activity\PageModule;
use Biz\service\activity\Page;
use Think\Exception;
/**
 * @deprecated
 */
class Coupon
{

    public static function getGoodsTips($uid, $goodsId, $shopId = 0)
    {
        try {

            $result = clsCoupon::goodsTips($uid, $goodsId, $shopId);

        } catch (\Exception $e) {

            throw $e;
        }

        return $result;
    }

    public static function canReceiveList($uid, $goodsId, $limit, $shopId)
    {
        try {
            $result = clsCoupon::canReceiveList($uid, $goodsId, $limit, $shopId);

        } catch (\Exception $e) {

            throw $e;
        }

        return array_values($result);
    }

    public static function shopExclusiveList($uid, $shopId, $limit)
    {
        try {
            $result = clsShopCoupon::shopExclusiveList($uid, $shopId, $limit);

        } catch (\Exception $e) {

            throw $e;
        }

        return array_values($result);
    }

    public static function getSelectList($uid, $tabId, $skuToken = '',$sCouponListJson='',$mealId=0)
    {
        try {
            $result = clsCoupon::selectList($uid, $tabId, $skuToken,0,[],$sCouponListJson,$mealId);
            if($result && is_array($result)) {
                foreach ($result as $k => $v) {
                    $result[$k]['expire_desc'] = self::formatExpireTime($v['end_time']);
                }
            }
        } catch (\Exception $e) {

            throw $e;
        }

        return $result;
    }

    public static function shopSelectList($uid, $tabId, $shopId, $skuToken = '')
    {
        try {

            $result = clsShopCoupon::shopSelectList($uid, $tabId, $shopId, $skuToken);

        } catch (\Exception $e) {

            throw $e;
        }

        return array_values($result);
    }

    public static function getMineList($uid, $cateId)
    {
        try {
            $result = clsCoupon::mineList($uid, $cateId,[],true);

        } catch (\Exception $e) {

            throw $e;
        }

        return $result;
    }

    public static function receive($uid, $couponId)
    {
        try {
            $result = [];

            if (empty($couponId)) {
                return $result;
            }

            if (strpos($couponId, ',') !== false) {
                throw new \Exception('系统错误');
            }


            $result = clsCoupon::receiveCoupon($uid, $couponId);

            tLog::coupon_receive_info('优惠券领取成功', ['uid' => $uid, 'coupon_id' => $couponId]);

            return $result;


        } catch (\Exception $e) {

            tLog::coupon_receive_warning('优惠券领取出现异常', [
                'uid'       => $uid,
                'coupon_id' => $couponId,
                'e_file'    => $e->getFile(),
                'e_msg'     => $e->getMessage(),
                'e_line'    => $e->getLine()
            ]);

            throw $e;
        }
    }

    /**
     * @desc 活动页领取优惠券
     * @param $uid
     * @param $moduleId
     * @param $couponId
     * @return mixed
     * @throws \Exception
     */
    public static function pageReceive($uid, $moduleId, $couponId)
    {
        $tag = Page::COUPON_TAG_NONE;
        $message = '领取成功';
        try {
            $moduleInfo = PageModule::getModuleInfoByModuleId($moduleId);
            $couponIds = explode(',', $couponId);
//            if (count($couponIds) == 1 && isset($moduleInfo['tab']) && $moduleInfo['tab'] != '') {
            if (count($couponIds) == 1) {
                $config = cCoupon::getConfig($couponId);
                $receive_rule = $config['receive_rule'] ?? 0;
                $hasCoupon = self::getUserHasCouponSum($couponId, $uid);
                if (($receive_rule > 0) && (($hasCoupon + 1) > $receive_rule)) {
                    $tag = Page::COUPON_TAG_RECEIVED;
                    throw new \Exception('已经领取过此券哦');
                }

                $sendComplete = self::getCouponReceived($couponId);
                if ($sendComplete) {
                    $tag = Page::COUPON_TAG_OVER;
                    //检查是否是最后一场
                    $pageId = isset($moduleInfo['page_id']) ? $moduleInfo['page_id'] : 0;
                    $lastModuleId = PageModule::getLastTabModuleIdByPageId($pageId);
                    $isLast = $lastModuleId == $moduleId;
                    if ($isLast) {
                        throw new \Exception('很遗憾，抢券活动已结束哦');
                    }
                    throw new \Exception('本时段已抢完，下场不要再错过哦');
                }

                $nowDate = date("Y-m-d H:i:s");
                $dateValid = $config['start_show_time'] < $nowDate && $config['stop_show_time'] > $nowDate;
                if (!$dateValid) {
                    throw new \Exception('不在活动时间内，领取失败');
                }
            }
            self::batchReceive($uid, $couponId, $tag);
            $tag = Page::COUPON_TAG_RECEIVED;
        } catch (\Exception $e) {
            $message = $e->getMessage();
            if ($tag == Page::COUPON_TAG_NONE) {
                throw $e;
            }
        }
        return compact('tag', 'message');
    }

    public static function batchReceive($uid, $couponIds, &$tag)
    {
        $except = [];
        $result = [];

        $couponIds = explode(',', $couponIds);

        if (empty($couponIds)) {
            return $result;
        }


        foreach ($couponIds as $couponId) {
            try {

                $result = clsCoupon::receiveCoupon($uid, $couponId);

            } catch (\Exception $e) {

                tLog::coupon_pullcoupon_warning('批量领取优惠券错误', [
                    'uid'        => $uid,
                    'coupon_ids' => $couponIds,
                    'e_file'     => $e->getFile(),
                    'e_msg'      => $e->getMessage(),
                    'e_line'     => $e->getLine()
                ]);

                $except[] = $e->getMessage();
            }
        }

        if (count($couponIds) > 1) {
            if (count($except) == count($couponIds)) {
                $tag = Page::COUPON_TAG_RECEIVED;
                throw new \Exception('已领过啦');
            }
        } else {
            if (!empty($except)) {
                throw new \Exception($except[0]);
            }
        }


        return true;

    }

    public static function pullCoupon($uid, $couponCode, $skuToken = '', $from = clsCoupon::PULL_COUPON_INAPP, $payAmount = 0)
    {
        try {

            $result = clsCoupon::pullCoupon($uid, $couponCode, $skuToken, $from, $payAmount);

        } catch (\Exception $e) {

            tLog::coupon_pullcoupon_warning('优惠券兑换出现异常', [
                'uid'       => $uid,
                'coupon_id' => $couponCode,
                'sku_token' => $skuToken,
                'e_file'    => $e->getFile(),
                'e_msg'     => $e->getMessage(),
                'e_line'    => $e->getLine()
            ]);

            throw $e;
        }

        return $result;

    }

    public static function getGoodsList($couponId,$sortType=0,$areaCode = 0,$page = 1){

        $result = clsShopCoupon::goodsList($couponId, $sortType,$areaCode, $page);


        return $result;
    }


    public static function admCacheCouponConfig($couponId)
    {
        if ($couponId > 0) {
            $data = mCouponConfig::get('*', ['coupon_id' => $couponId]);

            clsAdmCoupon::cacheCouponConfig($couponId, $data);
        }

    }

    public static function cacheCouponConfig($couponId)
    {
        if ($couponId > 0) {
            $data = mCouponConfig::get('*', ['coupon_id' => $couponId]);

            clsCoupon::cacheCouponConfig($couponId, $data);
        }

    }

    public static function mgtCacheCouponConfig($couponId)
    {
        if ($couponId > 0) {
            $data = mCouponConfig::get('*', ['coupon_id' => $couponId]);

            clsMgtCoupon::cacheCouponConfig($couponId, $data);
        }

    }

    public static function mgtCreate($shopId, $data)
    {
        try {

            $result = clsMgtCoupon::create($shopId, $data);

            if (!empty($result)) {
                array_map(function ($couponId) {
                    self::mgtCacheCouponConfig($couponId);
                }, $result);
            }

        } catch (\Exception $e) {

            tLog::coupon_mgtcreate_warning('商家创建优惠券出错', [
                'shop_id' => $shopId,
                'data'    => $data,
                'e_file'  => $e->getFile(),
                'e_msg'   => $e->getMessage(),
                'e_line'  => $e->getLine()
            ]);

            throw $e;
        }

        return $result;
    }

    public static function mgtEdit($shopId, $couponId, $data)
    {
        try {

            clsMgtCoupon::edit($shopId, $couponId, $data);

            if ($couponId > 0) {
                self::mgtCacheCouponConfig($couponId);
            }

        } catch (\Exception $e) {

            tLog::coupon_mgtedit_warning('商家编辑优惠券出错', [
                'shop_id'   => $shopId,
                'coupon_id' => $couponId,
                'data'      => $data,
                'e_file'    => $e->getFile(),
                'e_msg'     => $e->getMessage(),
                'e_line'    => $e->getLine()
            ]);

            throw $e;
        }

        return $couponId;
    }

    public static function mgtDetail($shopId, $couponId)
    {
        try {

            $result = clsMgtCoupon::detail($shopId, $couponId);


        } catch (\Exception $e) {

            tLog::coupon_mgtdetail_warning('商家编辑优惠券出错', [
                'shop_id'   => $shopId,
                'coupon_id' => $couponId,
                'e_file'    => $e->getFile(),
                'e_msg'     => $e->getMessage(),
                'e_line'    => $e->getLine()
            ]);

            throw $e;
        }

        return $result;
    }

    public static function mgtList($shopId, $page)
    {
        try {

            $result = clsMgtCoupon::lists($shopId, $page);

        } catch (\Exception $e) {

            throw $e;
        }

        return $result;
    }

    public static function admSearchCouponConfigList($where, $limit)
    {
        $resulst = clsAdmCoupon::getCouponConfigSearchList($where, $limit);

        return $resulst;
    }

    public static function mgtChangeStatus($shopId, $couponId, $status)
    {
        try {

            $result = clsMgtCoupon::changeStatus($shopId, $couponId, $status);

            if ($couponId > 0) {
                self::mgtCacheCouponConfig($couponId);
            }

            return $result;
        } catch (\Exception $e) {

            tLog::coupon_mgtchangestatus_warning('商家编辑优惠券状态', [
                'shop_id'   => $shopId,
                'coupon_id' => $couponId,
                'e_file'    => $e->getFile(),
                'e_msg'     => $e->getMessage(),
                'e_line'    => $e->getLine()
            ]);

            throw $e;
        }
    }

    public static function admSendToUser($adminUid, $couponId, $uidList, $reason, $sysMsgData = [])
    {
        try {

            $result = clsAdmCoupon::sendToUser($adminUid, $couponId, $uidList, $reason, $sysMsgData);


            return $result;
        } catch (\Exception $e) {

            tLog::coupon_admsend_warning('管理员发放优惠券', [
                'admin_uid'   => $adminUid,
                'coupon_id'   => $couponId,
                'uidlist'     => $uidList,
                'reason'      => $reason,
                'sysmsg_data' => $sysMsgData,
                'e_file'      => $e->getFile(),
                'e_msg'       => $e->getMessage(),
                'e_line'      => $e->getLine()
            ]);

            throw $e;
        }
    }

    public static function sendToUser( $couponId, $uidList, $reason, $sysMsgData = [])
    {
        try {

            $result = clsAdmCoupon::sendToUser(0, $couponId, $uidList, $reason, $sysMsgData);


            return $result;
        } catch (\Exception $e) {

            tLog::coupon_admsend_warning('系统活动发券', [
                'admin_uid'   => 0,
                'coupon_id'   => $couponId,
                'uidlist'     => $uidList,
                'reason'      => $reason,
                'sysmsg_data' => $sysMsgData,
                'e_file'      => $e->getFile(),
                'e_msg'       => $e->getMessage(),
                'e_line'      => $e->getLine()
            ]);

            throw $e;
        }
    }

    public static function admSendList($couponId)
    {
        $list = clsAdmCoupon::sendList($couponId);

        return $list;
    }

    public static function admSendUserList($couponId)
    {
        $list = clsAdmCoupon::sendUserList($couponId);

        return $list;
    }

    public static function admGetCloudTags()
    {
        $list = mCouponConfig::getCloudTags();

        return $list;
    }

    /**
     * @inheritdoc
     */
    public static function getCouponReceived($coupon_ids)
    {
        $list = mCouponConfig::getCouponReceived($coupon_ids);
        $response = [];
        if ($list) {
            foreach ($list as $val) {
                $response[$val['coupon_id']] = $val['total_count'] <= $val['received_count'];
            }
        }
        return is_array($coupon_ids) ? $response : $response[$coupon_ids];
    }

    /**
     * @inheritdoc
     */
    public static function getUserHasCouponSum($coupon_id, $uid)
    {
        return mCouponRecord::getUserHasCouponSum($uid, $coupon_id);
    }

    public static function admChangeStatus($couponId, $assume, $status)
    {
        if ($status == mCouponConfig::STATUS_CAN_NOT_RECEIVE) {

            clsCoupon::checkCouponCanDown($couponId,$assume);

        }

        $ret = mCouponConfig::upData($couponId, ['status' => $status]);
        if ($ret) {

            self::admCacheCouponConfig($couponId);
        }

        return $ret;
    }

    private static function recommendTogether($mineList, $skuIds, $cartList) {
		if ($mineList && $skuIds) {
			$newMineList = [];
			$actualGoodsAmount = $cartList['summary']['goods_amount'];
			if ($cartList['coupon'] && isset($cartList['coupon']['detract_amount'])) {
				$actualGoodsAmount = $actualGoodsAmount + $cartList['coupon']['detract_amount'];
			}
			foreach ($mineList as $item) {
				if ($item['assume'] == CouponConfig::COUPON_ASSUME_HHZ) {
					//存在更高优惠金额的平台优惠券
					if ($item['full_amount'] > $actualGoodsAmount) {
						$item['difference_amount'] = bcsub($item['full_amount'],$actualGoodsAmount ,2);
						if ($item['cate_scope'] == CouponConfig::CATE_SCOPE_ALL) {
                            $newMineList[] = $item;
                        } else if ($item['cate_scope'] == CouponConfig::CATE_SCOPE_NOT_ALL) {
						    $cateScope = array_filter(explode('|', $item['cate_ids']));
                            $goodsIds = [];
                            foreach ($cartList['list'] as $skuList) {
                                foreach ($skuList['sku_list'] as $sku) {
                                    $goodsIds[] = $sku['goods_id'];
                                }
                            }
                            $goodsList= Goods::Goods($goodsIds, Goods::FIELDS_GROUP_BASE);
					        foreach ($cateScope as $cateScopeItem) {
					            $tmpCates = explode('-',$cateScopeItem);
					            foreach ($goodsList as $goods) {
					                if ($tmpCates[1]) {
					                    if ($tmpCates[1] == $goods['second_category_id']) {
					                        $newMineList[]= $item;
					                        break;
                                        }
                                    } else {
					                    if ($tmpCates[0] == $goods['category_id']) {
                                            $newMineList[]= $item;
                                            break;
                                        }
                                    }
                                }
                            }
                        }
					}
				} else if ($item['assume'] == CouponConfig::COUPON_ASSUME_SHOP) {
					foreach ($cartList['list'] as $skuList) {
						//存在更高优惠的店铺卷
						if ($skuList['shop_info']['shop_id'] == $item['shop_info']['shop_id']) {
							if ($item['goods_range'] == mCouponConfig::GOODS_RANGE_ALL) {
								if ($item['full_amount'] > bcadd($item['detract_amount'], $skuList['summary']['goods_amount'], 2)) {
									$item['difference_amount'] = bcsub($item['full_amount'],$skuList['summary']['goods_amount'],2);
									$newMineList[] = $item;
								}
							} else if ($item['goods_range'] == mCouponConfig::GOODS_RANGE_PART) {
								$includeGoodsIds = explode(',', $item['include_goods_ids']);
								$goodsAmount = 0;
								foreach ($includeGoodsIds as $goodsId) {
									foreach ($skuList['sku_list'] as $sku) {
										if ($sku['goods_id'] == $goodsId) {
											$goodsAmount += bcmul($sku['buy_price'], $sku['buy_num'], 2);
										}
									}
								}
								if ($goodsAmount && $item['full_amount'] > $goodsAmount) {
									$item['difference_amount'] = bcsub($item['full_amount'], $goodsAmount, 2);
									$newMineList[] = $item;
								}
							}
						}
					}
				}
			}
			return $newMineList;
		} else {
			//如果未选中sku
			return $mineList;
		}
	}

	private static function recommendCurrent($mineList, $skuIds, $cartList = []){
		$newMineList = [];
		if ($mineList && $skuIds) {
			$actualGoodsAmount = $cartList['summary']['goods_amount'];
			if ($cartList['coupon'] && isset($cartList['coupon']['detract_amount'])) {
				$actualGoodsAmount = $actualGoodsAmount + $cartList['coupon']['detract_amount'];
			}
			foreach ($mineList as $item) {
				if ($item['assume'] == CouponConfig::COUPON_ASSUME_HHZ) {
					//存在更高优惠金额的平台优惠券

					if ($item['full_amount'] <= $actualGoodsAmount) {
					    if ($item['cate_scope'] == CouponConfig::CATE_SCOPE_ALL) {
                            $newMineList[] = $item;
                        } else if ($item['cate_scope'] == CouponConfig::CATE_SCOPE_NOT_ALL) {
					        $cateScope = array_filter(explode('|', $item['cate_ids']));
                            $goodsIds = [];
                            foreach ($cartList['list'] as $skuList) {
                                foreach ($skuList['sku_list'] as $sku) {
                                    $goodsIds[] = $sku['goods_id'];
                                }
                            }
                            $goodsList= Goods::Goods($goodsIds, Goods::FIELDS_GROUP_BASE);
					        foreach ($cateScope as $cateScopeItem) {
					            $tmpCates = explode('-',$cateScopeItem);
					            foreach ($goodsList as $goods) {
					                if ($tmpCates[1]) {
					                    if ($tmpCates[1] == $goods['second_category_id']) {
					                        $newMineList[]= $item;
                                            break;
                                        }
                                    } else {
					                    if ($tmpCates[0] == $goods['category_id']) {
                                            $newMineList[]= $item;
                                            break;
                                        }
                                    }
                                }
                            }

                        }
					}
				} else if ($item['assume'] == CouponConfig::COUPON_ASSUME_SHOP) {
                    $includeGoodsIds = explode(',', $item['include_goods_ids']);
					foreach ($cartList['list'] as $skuList) {
						//存在更高优惠的店铺卷
						if ($skuList['shop_info']['shop_id'] == $item['shop_info']['shop_id']) {
							if ($item['goods_range'] == mCouponConfig::GOODS_RANGE_ALL) {
								$totalShopAmount = 0;
								foreach ($skuList['sku_list']  as $sku) {
									$totalShopAmount += bcmul($sku['buy_num'], $sku['buy_price']);
								}
								if ($item['full_amount'] <= $totalShopAmount) {
									$newMineList[] = $item;
								}
							} else if ($item['goods_range'] == mCouponConfig::GOODS_RANGE_PART) {
								$goodsAmount = 0;
								foreach ($includeGoodsIds as $goodsId) {
									foreach ($skuList['sku_list'] as $sku) {
										if ($sku['goods_id'] == $goodsId) {
											$goodsAmount += bcmul($sku['buy_price'], $sku['buy_num'], 2);
										}
									}
								}
								if ($item['full_amount'] < $goodsAmount) {
									$newMineList[] = $item;
								}
							}
						}
					}
				}
			}
		}
		return $newMineList;
	}

	public static function recommendList($uid, $tabId, $skuIds, $areaCode, $appType)
	{
		$mineList = clsCoupon::mineList($uid, clsCoupon::CATE_ID_UNUSED,[]);
		array_multisort(array_column($mineList, 'detract_amount'),SORT_DESC,SORT_NUMERIC,array_column($mineList, 'end_time'), SORT_ASC, SORT_STRING, $mineList);
//		$cartList = Cart::cartList($uid, $skuIds, $areaCode, $appType);
		$currentRobbingSkuIds = Activitys::getCurrentLimitRobBySkuIds($skuIds);
		$skuIds = array_diff($skuIds, $currentRobbingSkuIds);
		$cartList = Cart::getClsCart($uid) -> cartList($uid, $skuIds, $areaCode, Cart::getAppSource($appType), $appType);
		if ($tabId == clsCoupon::TAB_TOGETHER_ORDER) {
			$list = self::recommendTogether($mineList, $skuIds, $cartList);
		} else if ($tabId == clsCoupon::TAB_CURRENT) {
			$list = self::recommendCurrent( $mineList, $skuIds,$cartList);
		} else {
			throw new \Exception('参数tab值不正确');
		}
		$isHasShopMax = $isHasNormalMax = false;
		foreach ($list as $k => $item) {
			$list[$k]['is_max'] = 0;
			$list[$k]['expire_desc'] = self::formatExpireTime($item['end_time']);
			if ($item['assume'] == mCouponConfig::COUPON_ASSUME_HHZ && $isHasNormalMax == false) {
				$isHasNormalMax = true;
				$list[$k]['is_max'] = 1;
			} else if ($item['assume'] == mCouponConfig::COUPON_ASSUME_SHOP && $isHasShopMax == false) {
				$isHasShopMax = true;
				$list[$k]['is_max'] = 1;
			}
		}
		array_multisort(array_column($list, 'is_max'), SORT_DESC, SORT_NUMERIC, $list);
		return $list;
	}

	private static function formatExpireTime($stopTime) {
		$expireTime = '';
		$expire = strtotime($stopTime) - time();
		if ($expire < 86400 * 7) {
			$expireDate = bcdiv($expire, 86400, 0);
			if ($expireDate >= 1) {
				$expireTime = "还剩" . (int)$expireDate  . "天过期";
			} else {
				$expireHourse = bcdiv($expire, 3600, 0);
				if ($expireHourse <= 0 ) {
					$expireHourse = 1;
				}
				$expireTime = "还剩" . $expireHourse . "小时过期";
			}
		}

		return $expireTime;
	}

	public static function recommendPromo($skuIds, $uid, $areaCode, $appSource, $appType)
	{
		$currentRobbingSkuIds = Activitys::getCurrentLimitRobBySkuIds($skuIds);
		$skuIds = array_diff($skuIds, $currentRobbingSkuIds);
		$mineList = clsCoupon::mineList($uid, clsCoupon::CATE_ID_UNUSED,[]);
		if (!$mineList) {
			return [];
		}
		if ($skuIds) {
            array_multisort(array_column($mineList, 'full_amount'),SORT_ASC,SORT_NUMERIC,array_column($mineList, 'end_time'), SORT_ASC, SORT_STRING, $mineList);
        } else {
            array_multisort(array_column($mineList, 'detract_amount'),SORT_DESC,SORT_NUMERIC,array_column($mineList, 'end_time'), SORT_ASC, SORT_STRING, $mineList);
        }
		$cartList = Cart::getClsCart($uid) -> cartList($uid, $skuIds, $areaCode, $appSource, $appType);

		$detractAmount = $cartList['summary']['s_coupon_amount'];
		if (isset($cartList['coupon']) && $cartList['coupon']) {
			$detractAmount += $cartList['coupon']['detract_amount'];
		}

		$couponList = self::recommendTogether( $mineList, $skuIds, $cartList);
		$couponListNotShop = [];
		foreach ($couponList as $item) {
			if (!$item['shop_info']['shop_id']) {
				$couponListNotShop[] = $item;
			}
		}
		$recommend = [];
		if (!$couponListNotShop) {
			if ($skuIds && $detractAmount) {
				$recommend['type'] = clsCoupon::TAB_RECOMMEND_TYPE_CURRENT;
				$recommend['promo'] = sprintf(clsCoupon::PROMO_INFO_4, floatval($detractAmount));
			}
		} else {
			if ($skuIds) {
				foreach ($couponList as $item) {
					if (!$item['shop_info']['shop_id']) {
						if ($detractAmount) {
							$recommend['type'] = clsCoupon::TAB_RECOMMEND_TYPE_TOGETHER_ORDER;
							$subBuyAmount = bcsub($item['full_amount'], $cartList['summary']['goods_amount'], 2) ;
							if (isset($cartList['coupon']) && $cartList['coupon']) {
								$subBuyAmount = bcsub($subBuyAmount, $cartList['coupon']['detract_amount'], 2);
							}
							$recommend['promo'] = sprintf(clsCoupon::PROMO_INFO_3, floatval($detractAmount),floatval( $subBuyAmount), floatval( $item['detract_amount']));
						} else {
							$recommend['type'] = clsCoupon::TAB_RECOMMEND_TYPE_TOGETHER_ORDER;
							$recommend['promo'] = sprintf(clsCoupon::PROMO_INFO_2, floatval(bcsub($item['full_amount'], $cartList['summary']['goods_amount'], 2)),floatval($item['detract_amount']));
						}
                        break;
					}
				}
			} else {
				foreach ($couponList as $item) {
					$recommend['type'] = clsCoupon::TAB_RECOMMEND_TYPE_TOGETHER_ORDER;
					$recommend['promo'] = sprintf(clsCoupon::PROMO_INFO_1, floatval( $item['detract_amount']) ,  strtotime(str_replace(".", "",  $item['stop_time'])) - time() <= 7 * 86400 ?  "即将过期"  : "" );
                    break;
				}
			}
		}
		return $recommend;
	}

	public static function mgtCouponList($shopId, $page = 1, $pagesize = 30)
    {
        if (!ShopSwitch::is_show_coupon($shopId)) {
            return ['list' => [], 'count' => 0];
        }
        $where = [ 'shop_id' => $shopId,
            'status' => mCouponConfig::STATUS_CAN_RECEIVE,
            'stop_time[>]' => date("Y-m-d H:i:s")];

        $couponList = mCouponConfig::getCouponList($where ,[($page - 1) * $pagesize, $pagesize], ['detract_amount' => 'ASC']);
        $count = mCouponConfig::getCount($where);

        return ['list' => array_values($couponList), 'count' => $count];
    }

    public static function shopCouponList($shopId, $uid)
    {
       $couponList = self::mgtCouponList($shopId, 1, 10);
       $recordList = CouponRecord::getUserCoupons($uid, array_column($couponList['list'], 'coupon_id'));
       $recordIds = array_column($recordList, 'coupon_id');
       $results = ['list' => [], 'count' => $couponList['count']];
       foreach ($couponList['list'] as $k => $couponInfo) {
           $couponInfo['start_time'] = str_replace('-', '.', substr($couponInfo['start_time'], 0, 10));
           $couponInfo['stop_time'] = str_replace('-', '.', substr($couponInfo['stop_time'], 0, 10));
           $results['list'][] = [
               'coupon_id' => $couponInfo['coupon_id'],
               'title' =>  sprintf("满%d减%d", $couponInfo['full_amount'], $couponInfo['detract_amount']),
               'full_amount' => $couponInfo['full_amount'],
               'detract_amount' => $couponInfo['detract_amount'],
               'start_time' => $couponInfo['start_time'],
               'stop_time' => $couponInfo['stop_time'],
               'time_range_desc' => $couponInfo['start_time'] . '-' . $couponInfo['stop_time'],
               'is_receive' => in_array($couponInfo['coupon_id'], $recordIds) ? 1 : 0,
           ];
       }

       return $results['list'];
    }





}